<template>

  <div class="jumbotron" v-if="isLoggedIn">
    <h2>学生列表</h2>
    <div>
      <input v-model="newStudent.name" placeholder="姓名" class="form-control" />
      <input v-model="newStudent.age" type="number" placeholder="年龄" class="form-control" />
      <select v-model="newStudent.gender" class="form-control">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
      <button @click="addStudent" class="btn btn-primary my-3">添加学生</button>
    </div>

    <ul class="list-group mt-3">
      <li class="list-group-item d-flex justify-content-between align-items-center" v-for="(student, index) in students"
        :key="index">
        {{ student.name }} - {{ student.age }}岁 - {{ student.gender }}
        <button class="btn btn-danger btn-sm" @click="deleteStudent(index)">
          删除
        </button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex'; // 引入store,可存储状态

const store = useStore(); //  获取store实例
const baseUrl= ref('http://127.0.0.1:5000');
const isLoggedIn = computed(() => store.state.isLoggedIn);
const newStudent = ref({
  id:0,
  name: '',
  age: 18,
  gender: '男',
});

const students = ref([]);
// 获取所有学生数据
const fetchStudents = async () => {
  try {
    const response = await fetch(`${baseUrl.value}/api/users`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
      }
    });

    if (!response.ok) {
      throw new Error('网络响应失败');
    }

    const data = await response.json();
    if (data.code === 200) {
      students.value = data.data
      .filter(student => student.id !== parseInt(store.state.user.id)) // 排除当前登录用户，登录用户信息存储在store中
      .map(student => ({
        id: student.id,
        name: student.name,
        age: student.age,
        gender: student.gender
      }));
    } else {
      console.error('获取学生列表失败:', data.message);
    }
  } catch (error) {
    console.error('获取学生列表时出错:', error);
  }
};

// 在组件挂载时获取数据
onMounted(() => {
  fetchStudents();
});
const addStudent = async () => {
  if (newStudent.value.name && newStudent.value.age) {
    try {
      const response = await fetch(`${baseUrl.value}/api/users`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('authToken')}`
        },
        body: JSON.stringify(newStudent.value)
      });

      if (!response.ok) {
        throw new Error('网络响应失败');
      }

      const data = await response.json();
      if (data.code == 200) {
        // 成功添加到服务器后更新前端列表
        newStudent.value.id = data.data.id;
        students.value.push({ ...newStudent.value });
        newStudent.value = { name: '', age: 18, gender: '男' };
      }else{
        console.log(data.message);
      }

    } catch (error) {
      console.error('添加学生失败:', error);
    }
  }
};

const deleteStudent = async (index) => {
  const studentToDelete = students.value[index];

  try {
    const response = await fetch(`${baseUrl.value}/api/users/${studentToDelete.id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('authToken')}`
      }
    });

    if (!response.ok) {
      throw new Error('网络响应失败');
    }

    const data = await response.json();
    if (data.code === 200) {
      // 删除成功后更新前端列表
      students.value.splice(index, 1);
    } else {
      console.error('删除失败:', data.message);
    }
  } catch (error) {
    console.error('删除学生时出错:', error);
  }
};
</script>